import struct, socket, time, urllib, urllib2
try:
    def at():
        print '_______ at()'
        host = "mc2015.myarena.ru"
        port = 25588
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))

        logindata = {'user':'SeR', 'password':'1234', 'version':'12'}
        data = urllib.urlencode(logindata)
        '''print('Sending data to login.minecraft.net...')
        req = urllib2.Request('https://login.minecraft.net', data)
        response = urllib2.urlopen(req)
        returndata = response.read() 
        returndata = returndata.split(":")
        mcsessionid = returndata[3]
        del req
        del returndata
        print("Session ID: " + mcsessionid)
        '''
        data = {'user':u'SeR','host':u'mc2015.myarena.ru','port':25588}
        mcsessionid = logindata['user']

        stringfmt = u'%(user)s;%(host)s:%(port)d'
        string = stringfmt % data
        structfmt = '>bh'
        packetbytes = struct.pack(structfmt, 2, len(string))+string.encode('utf-16BE')
        s.send(packetbytes)
        connhash = s.recv(1024)

        print ("Connection Hash: " + connhash)
        print ('Sending data to http://session.minecraft.net/game/joinserver.jsp?user=SeR&sessionId=' + mcsessionid + '&serverId=' + connhash + '...')
        req = urllib.urlopen('http://session.minecraft.net/game/joinserver.jsp?user=SeR&sessionId=' + mcsessionid + '&serverId=' + connhash)
        returndata = req.read()
        if(returndata == 'OK'):
            print('session.minecraft.net says everything is okay, proceeding to send data to server.')
        else:
            print('Oops, something went wrong.')

        time.sleep(5)

        # All above here works perfectly.
        enc_user = data['user'].encode('utf-16BE')
        #This line is probably where something's going wrong:
        packfmt = '>bih{}shiibBB'.format(len(enc_user))
        packetbytes = struct.pack(packfmt, 1, 23, len(data['user']), enc_user, 0, 0, 0, 0, 0, 0)
        print(len(packetbytes))
        print('Sending ' + packetbytes + ' to server.')
        s.send(packetbytes)
        x=1
        while x!=0:
            data = s.recv(1024)
            if data:
                print(data)
            else:
                x=0
except:
    print ' = = exception = = '
    while 1:
        at()
while 1:
    at()
